package org.omixed.flex;

import java.io.*;
import java.net.*;

import org.apache.log4j.Logger;

/**
 * @author Giles Velarde
 */
public class ShellClient
{
	private static ShellClient inst;
	private static String result;
	private final Socket socket;
	private String command;
	
	final static private Logger logger = Logger.getLogger("ShellClient");
	
	public static void main(String [ ] args)
	{
		try
		{
			logger.info(args[0]);
			InetAddress addr = InetAddress.getByName("localhost");
			inst = new ShellClient(addr, 53000, args[0]);
		} catch (Exception e)
		{
			logger.error(e.getMessage());
		}
	}
	
	/**
	 * 
	 * @param serverAddress
	 * @param port
	 * @throws IOException
	 */
	public ShellClient( final InetAddress serverAddress, final int port, final String command ) throws IOException, ShellException
	{
		socket = new Socket( serverAddress, port );
		this.command = command;
	}
	
	/**
	 * 
	 * @throws IOException
	 */
	void close() throws IOException
	{
		socket.close();
	}
	
	/**
	 * 
	 * @param filepath
	 * @throws IOException
	 * @throws ShellException
	 */
	public String send() throws IOException, ShellException
	{
		command += "\nEND.\n";
		
		OutputStream os = socket.getOutputStream();
		os.write( command.getBytes() );
		
		InputStream is = socket.getInputStream();
		InputStreamReader isr = new InputStreamReader(is);
		BufferedReader buf = new BufferedReader(isr);
		
		StringBuffer resultBuffer = new StringBuffer();
		
		String line;
		while ((line = buf.readLine()) != null) {	
			resultBuffer.append(line +"\n");
		}
		
		this.result = resultBuffer.toString();
		
		if (this.result.contains("Error:"))
		{
			throw new ShellException(this.result);
		}
		return this.result;
	}
	
	public String getResult()
	{
		return result;
	}
	
}